#!/bin/bash

# 检查 chillhop.txt 是否存在
if [ ! -f "chillhop.txt" ]; then
    echo "错误：当前目录未找到 chillhop.txt"
    exit 1
fi

# 读取并过滤有效曲目（仅保留 "ID!名称" 格式的行，跳过空行）
filtered_tracks=$(awk -F '!' '
    NF == 2 && $1 != "" && $2 != "" {  # 确保有两个字段且都非空
        gsub(/\r/, "", $0)             # 去除可能的Windows换行符
        print $0
    }
' chillhop.txt)

# 检查是否有有效曲目
if [ -z "$filtered_tracks" ]; then
    echo "错误：chillhop.txt 中无有效曲目（格式应为 'ID!名称'）"
    exit 1
fi

# 生成最终的 chillhopmenu.sh
cat > "chillhopmenu.sh" <<'EOF'
#!/bin/bash

# 配置项
CACHE_DIR="${HOME}/.cache/chillhop-player"
FFPLAY_PATH="ffplay"
STREAM_BASE_URL="https://stream.chillhop.com/mp3/"
DMENU_ARGS="-i -c"

# 嵌入的曲目列表（由 generate_chillhop_menu.sh 自动生成）
TRACKS=$(cat <<'TRACK_EOF'
EOF

# 插入过滤后的曲目到 TRACKS 变量中
echo "$filtered_tracks" >> "chillhopmenu.sh"

# 继续写入脚本剩余部分
cat >> "chillhopmenu.sh" <<'EOF'
TRACK_EOF
)

# 去除字符串首尾空格
trim() {
    local var="$*"
    var="${var#"${var%%[![:space:]]*}"}"
    var="${var%"${var##*[![:space:]]}"}"
    echo "$var"
}

# 解析嵌入的曲目
parse_tracks() {
    local line id name
    while IFS= read -r line; do
        [ -z "$line" ] && continue
        if [[ "$line" =~ ^([^!]+)!(.+)$ ]]; then
            id_raw="${BASH_REMATCH[1]}"
            name_raw="${BASH_REMATCH[2]}"
            id=$(trim "$id_raw")
            name=$(trim "$name_raw")
            name_escaped="${name//\'/\'\\\'\'}"
            id_escaped="${id//\'/\'\\\'\'}"
            echo "${name_escaped}|${id_escaped}"
        fi
    done <<< "$TRACKS"
}

# 主逻辑
main() {
    mkdir -p "${CACHE_DIR}"
    local parsed_tracks=$(parse_tracks)
    [ -z "$parsed_tracks" ] && { echo "错误：无有效曲目"; exit 1; }

    local selected=$(printf "%s\n" "$parsed_tracks" | dmenu $DMENU_ARGS | head -n1)
    [ -z "$selected" ] && { echo "用户取消选择"; exit 0; }

    local name=$(echo "$selected" | cut -d'|' -f1 | sed "s/'\\\'\"'/'/g")
    local id=$(echo "$selected" | cut -d'|' -f2 | sed "s/'\\\'\"'/'/g")
    local cache_file="${CACHE_DIR}/${id}.mp3"

    notify() {
        command -v "notify-send" &> /dev/null && notify-send "Chillhop" "$1"
    }

    if [ ! -f "${cache_file}" ]; then
        notify "正在下载：${name}"
        echo "下载中：${name}"
        if ! curl -sSL "${STREAM_BASE_URL}${id}" -o "${cache_file}"; then
            notify "下载失败：${name}"
            echo "下载失败"
            rm -f "${cache_file}"
            exit 1
        fi
        notify "下载完成：${name}"
    else
        echo "使用缓存：${cache_file}"
    fi

    notify "开始播放：${name}"
    echo "正在播放：${name}（按 q 退出）"
    ${FFPLAY_PATH} -nodisp -autoexit "${cache_file}"
    notify "播放结束：${name}"
}

main
EOF

# 给生成的脚本添加执行权限
chmod +x "chillhopmenu.sh"

echo "成功生成 chillhopmenu.sh（已嵌入 chillhop.txt 中的曲目）"
echo "可直接运行：./chillhopmenu.sh"

